import org.jsecurity.crypto.hash.Md5Hash
import org.springframework.validation.FieldError
import org.springframework.context.support.StaticMessageSource
import org.springframework.context.MessageSource
import org.springframework.context.support.DefaultMessageSourceResolvable
import org.springframework.context.MessageSourceResolvable
import org.springframework.context.NoSuchMessageException
import org.rowingmanager.io.IOUtil
import util.groovy.captcha.Captcha
import org.springframework.web.multipart.MultipartFile
import rowingmanager.domain.Country
import rowingmanager.domain.JsecRole
import rowingmanager.domain.User
import rowingmanager.domain.Organization
import rowingmanager.domain.JsecUserRoleRel
import rowingmanager.domain.Address;
class OrganizationController {
    static String AVATAR_LOCATION = "web-app/tmp/avatars/"
    static  links  = [links:[registerOrganization:"rowingmanager.domain.Organization",registerRower:"rowingmanager.domain.Rower"],controllers:['organization','rower']]
    def messageSource
    def fileService

    def countryList = {
       def clist = Country.list();
       render(contentType:"text/xml")
       {
            countries{
               for(i in clist){
                  countri {
                      id(i.id)
                      name(i.name)
                      code(i.code)
                  }
                }
            }
       }
    }

  /* def register = {
       if(request.method == 'POST'){
            def or = new Organization()

            or.title = params.org_title
            log.info("TITLE: " +params.org_title)
            or.taxid = params.org_taxid;
            or.type = params.org_type
            or.street = params.org_street
            or.city = params.org_city
            or.postalCode = params.org_postalCode
            or.phone = params.org_phone
            or.state = params.org_state
            or.country = Country.get(Integer.parseInt(params.org_country_id))     
            log.info("rowingmanager.domain.Country "+or.country.name)

            def usr = new User()
            usr.name = params.org_title
            usr.email = params.email
            usr.plainpassword = params.password
            if(usr.validate()){
               usr.password = new Md5Hash(params.password).toHex()
               usr.plainpassword = "notreal"
               File avatar = new File(AVATAR_LOCATION+usr.email+"\\avatar.jpg")
               log.info("Will check for avatar at this location "+avatar.absolutePath)
               if(avatar.exists()){
                   log.info("rowingmanager.domain.Image exists, trying to load bytes ")
                   usr.avatar = IOUtil.getBytesFromFile(avatar)

               }

                def organizationRole = JsecRole.findByName("rowingmanager.domain.Organization")
                if(!organizationRole){
                    log.info("Creating role rowingmanager.domain.Organization")
                    organizationRole = new JsecRole(name:"rowingmanager.domain.Organization")
                    organizationRole.save()
                }
               or.user = usr
                if(or.save()){
                    log.info("Adding role rowingmanager.domain.Organization to user")
                    new JsecUserRoleRel(user:usr,role:organizationRole).save()
                    log.info("rowingmanager.domain.Organization saved! rowingmanager.domain.User password is "+usr.password)
                    render ("Success! rowingmanager.domain.Organization registered")
                }
                else{
                    or.errors.allErrors.each {log.debug(it)}
                    log.info("Something went wrong - Could not save organization!")
                }
           }
           else{
           log.info("user did not validate")
           log.info("password is " +usr.password)
           MessageSourceResolvable msr
           def errList = []
           def currentMessage
           usr.errors.allErrors.each { 
              String [] codes = it.getCodes()
               for(code in codes){
                   log.info("CODE : "+code)
                   msr = new DefaultMessageSourceResolvable(code)
                   try{
                       currentMessage = messageSource.getMessage(msr,new Locale("en","US"))
                       log.info("mesage ="+currentMessage)
                       errList.add(currentMessage)
                   }catch(NoSuchMessageException e){println e.message}
               }
              }
               render  errList.each { log.error(it)}
            }
            
       }
   }  */

  def registerOrganization = {
    def organization = new Organization()
    organization.address = new Address()
    def captcha = new Captcha()
    session.captcha = captcha
    log.info("Generating captcha with result ${captcha?.result}")
    return [user:new User(),address:new Address(),organization:organization,clist:Country.list(),secondary_links:links]
  }

  def save = {
     println " params captcha : ${params?.captchaValue}, expected: ${session?.captcha?.result}"
     println "${params.inspect()}"
      def usr = new User()
      bindData(usr,params,[include:'email'],"user")
      usr.password = new Md5Hash(params.user.password).toHex()
      def organizationRole = JsecRole.findByName("Organization")
      if(!organizationRole){
        log.info("Creating role - Organization")
        organizationRole = new JsecRole(name:"Organization")
        organizationRole.save()
       }

      def address = new Address()
      bindData(address,params,[exclude:'country'],"address")
      address.country = Country.get(params.address.country)

      def org = new Organization(params['organization'])
      org.address = address
      org.addToUsers(usr)

      MultipartFile file = request.getFile('logo');
      
      if(!file.isEmpty())
        org.avatar = fileService.uploadAndGetImage(file,usr.email)
      else
        log.info("No picture specified...skipping resize")

      def c = (session?.captcha?.result.toString() == params?.captchaValue)
        log.debug("c returns ${c} | captcha from session: ${session?.captcha?.result.toString()} | captcha from request: ${params?.captchaValue}")
      if(org.validate() && c) {
       org.save()
       new JsecUserRoleRel(user:usr,role:organizationRole).save()
       flash.message = "Organization [${org.title}] saved!"
       println "organization saved!"
       def captcha = new Captcha()
       session.captcha = captcha
       redirect(action:'registerOrganization',model:[organization:new Organization(),user:new User(),clist:Country.list()])
      }
      else {
       println "didn't save!"
       flash.captcha = ''
       if(!c){ //incorrect captcha
         println params.inspect()
         flash.captcha = 'Incorrect captcha!'
         log.debug ('Incorrect captcha value')
       }
       if(org.hasErrors()) {
         org.errors.each { println it }
       }
       render(view:'registerOrganization',model:[organization:org,user:usr,clist:Country.list()])

     }
    
  }

  def checkCaptcha = {
    println("checking captcha..")
    println  params.inspect()
    println "result is "+ session?.captcha?.result
    if(session?.captcha?.result.toString() == params?.captchaValue)
      render '''<img src="/RowingManagement/icons/green_check.jpg" alt="correct"/> '''
    else
      render '''<img src="/RowingManagement/icons/red_cross.png" alt="wrong!"/> '''
  }
  

}
